import axios from 'axios';
import { router } from '@/router';
import { NstdMessage } from 'nstd-components-pc-v3';
import { useAuthStore } from '@/stores/auth/index.jsx';
import { isLocalDev, isPreviewDev } from '@/utils/env.js';
import csncUtils from 'csnc-utility-js';

// 创建axios实例 这个方法先不导出给外部使用
const createRequest = (config) => {
  return axios.create(config);
};
const request = createRequest({
  baseURL: (window.location.host.includes('localhost') ? 'http://25.55.58.184:19000' : window.location.origin) + '/bdz-api',
  timeout: import.meta.env.VITE_APP_API_TIMEOUT
});

// request拦截器
// 还可以进一步封装
request.interceptors.request.use(
  async (config) => {
    config.headers.terminal = 1;
    // config = await csncUtils.preventTamperV2(config, sessionStorage.getItem('Authorization') || '');
    const auth = useAuthStore();
    const token = auth.token;
    if (token) {
      config.headers.Authorization = auth.token;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// response拦截器
// 还可以进一步封装
request.interceptors.response.use(
  (response) => {
    const res = response.data;
    const isTemper = csncUtils.isTamper(response);
    if (isTemper) {
      NstdMessage.error('数据已被篡改');
      return;
    }
    // if (res.code !== 200) {
    //   // NstdMessage.error(res.msg || 'Error');
    //   return Promise.reject(res);
    // }
    if (response.config.responseType === 'blob') {
      return response;
    }
    if ((isLocalDev() || isPreviewDev()) && res.code !== 200) {
      NstdMessage.error(res.msg || 'Error');
    }

    return res;
  },
  ({ response }) => {
    const { status: responseStatus, data: responseData } = response;
    if (responseStatus === 401) {
      NstdMessage.error(responseData?.msg || 'unauthorized');
      router.push({ path: '/login', replace: true });
    }
    return Promise.reject(responseData);
  }
);
export default request;
